package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {


    @Resource
    private IUserService userService;
    @Resource
    private IFollowService followService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询博文详情
     * @param id
     * @return
     */
    @Override
    public Result queryBlogById(Long id) {
        Blog blog = getById(id);
        if (blog == null) {
            return Result.fail("笔记不存在");
        }
        //补充博文作者信息
        setUserInfo(blog);
        // todo 设置isLike笔记是否被点赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }

    /**
     * 查询热门笔记
     * @param current
     * @return
     */
    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            setUserInfo(blog);
            // todo 设置博文是否被点赞 isLike
            isBlogLiked(blog);

        });
        return Result.ok(records);
    }

    /**
     * 点赞笔记
     * @param id
     * @return
     */
    @Override
    public Result likeBlog(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        String userId = UserHolder.getUser().getId().toString();
        //从redis中获取点赞用户 id 使用zSet 利用时间戳升序排序
        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        // 2.判断当前用户是否已经点赞
        if (score== null) {
            // 2.2 如果没有点赞，则点赞 并将用户id保存到redis的Zset集合中 更新点赞数量

            boolean flag = update().setSql("liked=liked+1").eq("id", id).update();
            if( flag){
                // 更新redis
                stringRedisTemplate.opsForZSet().add(key, userId, System.currentTimeMillis());
            }
            }else {
            // 2.1 如果已经点赞，则不能重复点赞 取消点赞 将用户id从redis的Zset集合中移除
            boolean flag = update().setSql("liked=liked-1").eq("id", id).update();
            if( flag){
                // 更新redis
                stringRedisTemplate.opsForZSet().remove(key,userId);
            }

        }
        return Result.ok(id);
        }

    @Override
    public Result queryBlogLikes(Long id) {
        String key = RedisConstants.BLOG_LIKED_KEY + id;
        // 查询top5 根据key来查询zset集合 获取点赞用户id zset集合中分数从高到低排序
        // 最先点赞的在最前
        Set<String> top5 = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if (top5 == null || top5.isEmpty()) {
            return Result.ok();
        }
        List<Long> listTOP5 = top5.stream().map(Long::valueOf).collect(Collectors.toList());
        String join = StrUtil.join(",", listTOP5);
        List<User> users = userService.query().in("id", listTOP5).last("ORDER BY FIELD(id,"+ join+  ")").list();
        List<UserDTO> userDTOS = users.stream()
                .map(user -> BeanUtil.copyProperties(user, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(userDTOS);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSaved = this.save(blog);
        if (!isSaved) {
            return Result.fail("新增笔记失败");
        }
        // 查询笔记作者的粉丝  查询我自己的粉丝 当我发布笔记后，所有粉丝都会收到推送
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        // 推送笔记id到粉丝
        for (Follow follow : follows) {
            // 获取粉丝id
            Long userId = follow.getUserId();
            // 给粉丝发送消息
            String key = RedisConstants.FEED_KEY + userId;
            stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
        }
        // 返回id
        return Result.ok(blog.getId());
    }

    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        // 获取当前用户
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FEED_KEY + userId;
        // 查询收件箱
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate
                .opsForZSet()
                .reverseRangeByScoreWithScores(key, 0, System.currentTimeMillis(), offset, 3);
        // 非空判断
        if (typedTuples == null || typedTuples.isEmpty()) {
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>(typedTuples.size());
        long minTime=0;
        Integer os=1;
        // 解析数据
        for (ZSetOperations.TypedTuple<String> typedTuple : typedTuples) {
            Long id = Long.valueOf(typedTuple.getValue());
            ids.add(id);
            long Time = typedTuple.getScore().longValue();
            if(Time==minTime){
                os++;
            }else {
                os=1;
            }
            minTime = Time;
        }
        // 根据id 查询笔记
        String idsStr = StrUtil.join(",", ids);
        List<Blog> blogs = query().in("id", ids).last("ORDER BY FIELD(id," + idsStr + ")").list();
        for (Blog blog : blogs) {
            setUserInfo(blog);
            isBlogLiked(blog);
        }
        // 封装return
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setOffset(os);
        scrollResult.setMinTime(minTime);
        return Result.ok(scrollResult);
    }

    // 判断当前用户是否已经点赞
   private void isBlogLiked(Blog blog){
        String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();
       if (UserHolder.getUser() == null) {
           // 用户未登录 不需要查询
           return;
       }
        String userId = UserHolder.getUser().getId().toString();

        Double score = stringRedisTemplate.opsForZSet().score(key, userId);
        blog.setIsLike(score != null);
   }

    // 查询用户信息
    private void setUserInfo(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }


}
